package pers.jsan.litheopen.security.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import pers.jsan.litheopen.security.cache.CacheClientManager;
import pers.jsan.litheopen.security.exception.LitheAuthenticationException;
import pers.jsan.litheopen.security.oauth.ClientContext;
import pers.jsan.litheopen.security.oauth.ClientContextHolder;
import pers.jsan.litheopen.security.oauth.model.ClientAccess;
import pers.jsan.litheopen.security.prover.AuthenticationManager;
import pers.jsan.litheopen.utils.CodeEnum;
import pers.jsan.litheopen.utils.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClientOnlineInterceptor implements HandlerInterceptor {

    private final static String CLIENT_TOKEN = "token";

    private AuthenticationManager authenticationManager;

    private CacheClientManager redisClientManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        try {
            if(authenticationManager.isClientOnlineDisable()) {
                throw new LitheAuthenticationException("客户端在线校验被禁止");
            }
            String token = request.getParameter(CLIENT_TOKEN);
            ClientAccess clientAccess = redisClientManager.getAccessToken(token);
            if(null == clientAccess) {
                throw new LitheAuthenticationException("凭证错误");
            }
            ClientContext clientContext = new ClientContext();
            clientContext.setClientAccess(clientAccess);
            ClientContextHolder.set(clientContext);

        } catch (LitheAuthenticationException e) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(JSONObject.toJSONString(new Result(CodeEnum.AUTHENTICATION_ERROR.get(), null, e.getMessage())));
            return false;
        }
        return true;
    }

    public ClientOnlineInterceptor setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        return this;
    }

    public AuthenticationManager getAuthenticationManager() {
        return authenticationManager;
    }

    public CacheClientManager getRedisClientManager() {
        return redisClientManager;
    }

    public ClientOnlineInterceptor setRedisClientManager(CacheClientManager redisClientManager) {
        this.redisClientManager = redisClientManager;
        return this;
    }
}
